#include "ad.h"
#include "mainwindow.h"
#include "ui_ad.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include <QFile>
#include <QLabel>
#include <QPixmap>

ad::ad(QWidget *parent) : QMainWindow(parent), ui(new Ui::ad) {
  ui->setupUi(this);
  pic_init();

  // 添加无操作检测定时器
  inactivityCheckTimer = new QTimer(this);
  //  connect(inactivityCheckTimer, &QTimer::timeout, this,
  //  &ad::checkInactivity); inactivityCheckTimer->start(1000); // 每秒检查一次
}

ad::~ad() {
  if (imageTimer->isActive()) {
    imageTimer->stop(); // 停止定时器
  }
  delete ui;
}

void ad::pic_init() {
  // 1. 修正图片路径（使用本地路径或资源路径）
  imageList << ":/img/ad1.png"
            << ":/img/ad2.png"
            << ":/img/ad3.png";

  // 2. 检查路径是否有效
  for (const QString &path : imageList) {
    if (!QFile::exists(path)) {
      qWarning() << "Image file not found:" << path;
    }
  }

  // 3. 设置QLabel并显示第一张图片
  ui->label->setScaledContents(true);
  if (!imageList.isEmpty()) {
    QPixmap pixmap(imageList.first());
    if (!pixmap.isNull()) {
      ui->label->setPixmap(pixmap);
    } else {
      qWarning() << "Failed to load image:" << imageList.first();
    }
  }

  // 4. 初始化定时器
  imageTimer = new QTimer(this);
  connect(imageTimer, &QTimer::timeout, this, &ad::showNextImage);
  imageTimer->start(3000);
}

// 槽函数：切换到下一张图片
void ad::showNextImage() {
  if (imageList.isEmpty())
    return;

  currentIndex = (currentIndex + 1) % imageList.size();
  QPixmap pixmap(imageList[currentIndex]);

  // 检查图片是否加载成功
  if (!pixmap.isNull()) {
    ui->label->setPixmap(pixmap);
  } else {
    qWarning() << "Failed to load image:" << imageList[currentIndex];
  }
}
